/* OAuth common js function
*
* */

$(document).ready( function(){
	YSI.OAuth.init();
});


var oauthTimer = 0;
var YSI = YSI || {};
YSI.OAuth = (function() {
	var callbackFunc = null;
	var clickCB = null;
	var batchId = null;
	var foldersUrl = '/folders?phi_action=app/addFileToWorkspaceFolder'; /* The URL of workspace folder */
	var loginUrl = '/';
	var act = 0;
	var oauthButtonProviders = ['yahoo', 'facebook'];

	function init() {
		setOAuthDialogDefaults();
		bindSignIn();
		bindCloseOkayPopup();
		bindMigrateToCorpUserPopup();
		bindDisplayLoginType();
	}

	function setClickCallBack(clickCallback) {
		if(typeof clickCallback == 'function') clickCB = clickCallback;
	}

	function setCallBack(succCallback, clickCallback) {
		if(typeof succCallback == 'function') callbackFunc = succCallback;
	}

	function bindSignIn() {
		$('.ysi_oauth_signin').unbind('click').bind('click', function(e) {
			var popupWin = null;
			var provider = $(this).attr('provider');
			if(typeof clickCB == 'function') clickCB(provider);
			var importcontact = $(this).attr('importcontact') ? 1 : 0;
			var importcontact_selected = $(this).attr('importcontact_selected') ? 1 : 0;

			e.preventDefault();
			e.stopPropagation();

			switch(provider) {
				case 'yahoo':
				tracklink (getPageName(), "ysi_bindYahooSignin");
				$('.oauth_provider_nm').html('Yahoo');
				popupWin = openSocialConnect('/socialOpenIdConnectLogin?service_api=init&provider_id=yahoo&importcontact='+importcontact, 'Yahoo.com', 510, 480 );
				break;
				case 'facebook':
				tracklink (getPageName(), "ysi_bindFacebookSignin");
				$('.oauth_provider_nm').html('Facebook');
				popupWin = openSocialConnect('/socialOpenIdConnectLogin?service_api=init&provider_id=facebook&importcontact='+importcontact, 'Facebook.com', 950, 550 );
				break;
				case 'google':
				tracklink (getPageName(), "ysi_bindGoogleSignin");
				$('.oauth_provider_nm').html('Gmail');
				popupWin = openSocialConnect('/socialOpenIdConnectLogin?service_api=init&provider_id=google&importcontact='+importcontact, 'Google.com', 510, 480 );

				break;
				default:
				break;
			}

			if(oauthTimer) {
				clearInterval(oauthTimer);
			}

			oauthTimer = setInterval(function() {
				if(popupWin.closed && isLogin()) {
					clearInterval(oauthTimer);

					var oauthJson = null;
					var provider_id = null;
					var userReg   = false;
					var userLogin = false;
					try {
						oauthJson = eval("("+$.cookie('oauth')+")");
						provider_id = oauthJson != null && oauthJson.provider_id;
						userReg   = oauthJson != null && oauthJson.user_registed;
						userLogin = oauthJson != null && oauthJson.user_login;
						loginUrl = oauthJson != null && oauthJson.oauth_url;
					} catch(e) {}

					if (importcontact && oauthJson.oauth_request_token) {
						displayImportContact(provider_id, importcontact_selected);
					} else if(userReg) {
						act = 1;
						//$('#basic-modal-content:visible').dialog('close');
						displayCreateAccount(provider_id);
						return true;
					} else if(userLogin) {
						act = 2;
						$('#basic-modal-content:visible').dialog('close');
						displayFirstLoginAccount();
						return true;
					} else {
						$('#basic-modal-content:visible').dialog('close');
						return true;
					}
				}
			}, 1000);
			return false;
		});
	}


	//Dislay: Result of Create Account
	function displayCreateAccount(provider_id) {

		if(callbackFunc) {
			user_logged_in = true; // global variable of uploading copmonent
			callbackFunc({success:true, method:'oauth'});
			return false;
		}

		var cookieUname = $.cookie("uname");
		var cookieEmail = $.cookie("emailAddress");

		if(cookieUname !='' && cookieEmail != '') {
			$('.oauth_created_name').html(cookieUname+',');
			$('.oauth_created_email').html(cookieEmail);
		} else {
			window.location='/login';
		}

		$(".oauth_create_account_dialog:last").dialog({
			open: function (event, ui) {
				$(".ui-dialog-titlebar-close").hide();
				$(".ui-dialog .ui-dialog-titlebar").hide();
				$(".ui-dialog-content").css('padding','10px');
				$(".oauth_create_account_dialog:last").parent().css('width', 490); /* only effort oauth_create_account_dialog */
			}
		});

		$(".oauth_create_account_dialog:last").dialog('open');

		if( provider_id == 'yahoo') {
			$('.oauth_create_acct_yahoo').show();
		} else if( provider_id == 'facebook') {
			$('.oauth_create_acct_facebook').show();
		}

		$(".oauth_close_ok").bind('click', function(e) {
			e.preventDefault();
			e.stopPropagation();

			$('#basic-modal-content:visible').dialog('close');
			user_logged_in = true; // global variable of uploading copmonent

			if($('#ysi_dlg_lrg20:visible').length>0) {
				$('#ysi_from').val($.cookie("emailAddress"));
				$('#ysi_upload_row_from').hide();
				$(".ui-dialog-content").dialog("close");
			} else if($('.ysi_oauth_signin:visible').attr('alt') == 'validateAndDownload') { /* VRI usecase */
				$(".ui-dialog-content").dialog("close");
				downloadVRI();
			} else if($('.oauth_create_account_dialog:visible').length > 0) { /* In case of first registered */
				$(".ui-dialog-content").dialog("close");
				if(YSI.OAuth.batchId) {
					window.location = foldersUrl + '&batchId=' + YSI.OAuth.batchId.wsBatchId + '&batchFwd=1';
				} else if ($.cookie('encInviteId')) {
					window.location = '/folders?encInviteId='+$.cookie('encInviteId');
				} else {
					window.location = fistTimeUrl;
				}
			} else if($('#ysi_exist_id_sender:visible').length > 0) { /* From sending page as GST */
				$(".ui-dialog-content").dialog("close");
				window.location = '/';
			} else if(YSI.OAuth.batchId) {
				if(location.href.indexOf('addFileToWorkspaceFolder')!== -1 && YSI.OAuth.batchId){
					window.location = location.href + '&batchId=' + YSI.OAuth.batchId.wsBatchId + '&batchFwd=1';
				} else {
					if(YSI.OAuth.batchId.wsBatchId){
						window.location = foldersUrl + '&batchId=' + YSI.OAuth.batchId.wsBatchId + '&batchFwd=1';
					} else {
						window.location = location.href; // Leave the user on the same page but reload it
					}
				}
			} else {
				window.location = loginUrl;
			}
		});
	}

	function displayImportContact(provider, autoSelected) {
        autoSelected = autoSelected || false;
        $('#import_contacts').qtip('hide'); // from /mycontacts page
		$('#oauth_import_contact_dialog_btn').click();
	    $('#oauth_import_contact_list').empty();
        $('#oauth_import_contact_selected').html('');
        $.post('/dl?phi_action=app/importContact', {"provider": provider}, function(data){
            if (data.success) {
				$('#oauth_import_contact_dialog_close').show();
	            $('#provider-logo').attr('class', 'ref_third_party ' + 'ref_' + provider);
                var html = '<table width="100%">';
                html += '<thead>';
                html += '<tr>';
                html += '<th class="checkbox"><input type="checkbox" id="import_contacts_all"></th>';
                html += '<th class="email">Email</th>';
                html += '<th class="first">First Name</th>';
                html += '<th class="last">Last Name</th>';
                html += '</tr>';
                html += '</thead>';
                html += '<tbody>';
                $.each(data.contacts, function(index, value) {
                    html += '<tr>';
                    html += '<td><input type="checkbox" value="'+value.email+'|'+value.first+'|'+value.last+'"></td>';
                    html += '<td>'+ellipsis(value.email, 34)+'</td>';
                    html += '<td>'+ellipsis(value.first, 18)+'</td>';
                    html += '<td>'+ellipsis(value.last, 18)+'</td>';
                    html += '</tr>';
                });
                html += '</tbody>';
                html += '</table>';
	            $('#oauth_import_contact_list').html(html);
	            $('#oauth_import_contact_subtext').html(data.contacts.length + ' contacts from ' + YSI.OAuth.providers[provider]);

                $('#import_contacts_all').click( function() {
                    $('#oauth_import_contact_list input:checkbox').attr('checked',$('#import_contacts_all').is(':checked'));
                    setSelectedImportContactText();
                });


                $('#oauth_import_contact_dialog input:checkbox').click(function(e) {
                    setSelectedImportContactText();
                });

                $('#oauth_import_contact_add').unbind('click').click(function(e) {
				    var allVals = [];
				    $('#oauth_import_contact_dialog input[id!="import_contacts_all"]:checkbox:checked').each(function() {
                        var contact = $(this).val().split('|')
				    	allVals.push(contact[0]);
				    });
				    $('#ysi_referralEmailRecipients').val($.trim($.trim($('#ysi_referralEmailRecipients').val()) + "\n" + allVals.join("\n")));
                    $('#contact_status').html(parseInt($('#contact_status').html()) + allVals.length);
                    $('#sendReferralEmailLink').data(provider+'ContactsImported',allVals.length);
				    $('#oauth_import_contact_dialog_close').click();
                });

                $('#oauth_import_contact_import').unbind('click').click(function(e) {
				    var contacts = [];
				    $('#oauth_import_contact_dialog input[id!="import_contacts_all"]:checkbox:checked').each(function() {
                        var contact = $(this).val().split('|')
                        contacts.push({'email': contact[0], 'first': contact[1], 'last': contact[2]});
				    });
                    if (!contacts.length) return;
				    $('#oauth_import_contact_list').css('display', 'none');
				    $('#oauth_import_contact_importing').css('display', 'table-cell');
                    $.post('/mycontacts?phi_action=app/modifyContact', {
                        contacts: $.toJSON(contacts),
                        taskCompleted: 1
                    }, function(data) {
				        $('#oauth_import_contact_dialog_close').click();
                        var extra = data.userTask ? '&taskCompleted=IMPC' : ''; 
                        window.location="/mycontacts?e=1"+extra;
                    }, 'json');
                });

                $('#oauth_import_contact_cancel').click(function(e) {
                	$('#oauth_import_contact_dialog_close').click();
                });

                function setSelectedImportContactText() {
                    var count = $('#oauth_import_contact_dialog input[id!="import_contacts_all"]:checkbox:checked').length;
                    var countMsg = count ? (count + ' selected') : '';
                    $('#oauth_import_contact_selected').html(countMsg);
                }
            } else {
                // error
            }

            if (autoSelected) {
                $('#import_contacts_all').attr('checked', true);
                $('#import_contacts_all').click();
                $('#import_contacts_all').attr('checked', true);
            }
        });
		
	}

	//Dislay: Result of Login account (Frist time and more)
	function displayFirstLoginAccount() {

		if(callbackFunc) {
			user_logged_in = true; // global variable of uploading copmonent
			callbackFunc({succ:true, method:'oauth'});
			return false;
		}

		var cookieUname = $.cookie("uname");
		var cookieEmail = $.cookie("emailAddress");
		if(cookieUname !='' && cookieEmail != '') {
			$('.oauth_created_name').html(cookieUname+',');
			$('.oauth_created_email').html(cookieEmail);
		} else {
			window.location='/login';
		}

		user_logged_in = true; // global variable of uploading copmonent

		if($('#ysi_dlg_lrg20:visible').length>0) { /* GST and more 2MB */
			$('#ysi_upload_row_from').hide();
			$(".ui-dialog-content").dialog("close");
		} else if($('.ysi_oauth_signin:visible').attr('alt') == 'validateAndDownload') { /* VRI usecase */
			$(".ui-dialog-content").dialog("close");
			downloadVRI();
		} else if($('.oauth_create_account_dialog:visible').length > 0) { /* In case of first registered */
			$(".ui-dialog-content").dialog("close");
			$('#ysi_upload_row_from').hide();
		} else if($('#ysi_exist_id_sender:visible').length > 0) { /* From sending page as GST */
			$(".ui-dialog-content").dialog("close");
			window.location = '/';
		} else if(location.href.match(/login/i) == 'login' || location.href.match(/litesignup/i) == 'litesignup') { /* From login & litesignup page */
			if(YSI.OAuth.batchId){
				window.location = location.href + '&batchId=' + YSI.OAuth.batchId.wsBatchId + '&batchFwd=1';
			} else {
				window.location = loginUrl;
			}
		} else if(YSI.OAuth.batchId) {
			if(location.href.indexOf('addFileToWorkspaceFolder')!==-1 && YSI.OAuth.batchId){
				window.location = location.href + '&batchId=' + YSI.OAuth.batchId.wsBatchId + '&batchFwd=1';
			} else {
				if(YSI.OAuth.batchId.wsBatchId){
					window.location = foldersUrl + '&batchId=' + YSI.OAuth.batchId.wsBatchId + '&batchFwd=1';
				} else {
					window.location = location.href; // Leave the user on the same page but reload it
				}
			}
		} else {
			location.reload(); // Leave the user on the same page but reload it
		}
	}


	function downloadVRI() {
		var emailOAuth = $.cookie('emailAddress');
		var params = {act		: 'checkRcptList',
			dl_link	: dl_link,
			ysi_email	: emailOAuth,
			check_rcpt_list: true,
		pwd		: ''};

		$.post("/dl?phi_action=app/validateAndDownload", params, function(data){
			if(data) { // email is in recipient list
				var params = ['act', 'ysi_email', 'rurl', 'pwd'];
				var dat = { act			: 'forwardToDownload',
					ysi_email	: emailOAuth,
					rurl		: dl_link,
					pwd			: ''
				};
				submitHiddenForm(dat, params, 'dl?phi_action=app/validateAndDownload');
			} else {
				showError(/*<sl:translate>*/'Email address not correct'/*</sl:translate>*/, /*<sl:translate>*/'Please check the email address provided.  The sender did not specify this email as a recipient.'/*</sl:translate>*/);
			}
		});
	}

	function bindMigrateToCorpUserPopup() {

		$(".ysi_passwd_setup_openid:last").dialog({
			autoOpen: false,
			open: function (event, ui) {
				$(".ui-dialog-titlebar-close").hide();
				$(".ui-dialog .ui-dialog-titlebar").hide();
				$(".ui-dialog-content").css('padding','0px');
			}
		});

		$(".login_popup_close").bind('click', function(e) {
			$("#ysi_exist_id_sender").hide();
			$("#basic-modal-content .login_box_wrapper .login-header-title, .oauth_social_box_wrapper .login-header-title").show();
			$(".login_box_wrapper").css("padding-top","30px");
			$(".oauth_social_box, .oauth_divide_wrapper").css("margin-top","30px");
			$(".ui-dialog").height(300);

			$('.ysi_passwd_setup_openid:visible').dialog('close');
			return false;
		});

		$("#oauth_migrate_cont").bind('click', function(e) {
			logout();
			location.href='/reset_password';
			return false;
		});
	}

	function bindCloseOkayPopup() {
		$(".oauth_close_ok:visible").click(function() {
			$(".oauth_create_account_dialog:visible, .oauth_first_login_dialog:visible").dialog('close');
		});
	}

	function bindDisplayLoginType() {
		var provider_id = $('.oauth_more_options').attr('provider_id');
		var options = {domain: 'hightail.com', path:'/'};

		if(provider_id != '' && ($.inArray(provider_id, oauthButtonProviders) >= 0) && (typeof is_referral=='undefined' || !is_referral)) {
			$('.oauth_social_box_wrapper .ysi_oauth_signin').each(function(idx) {
				if($(this).attr('provider') != provider_id) {
					$(this).parent().hide();
					$('.oauth_more_options').show();
				}
			});
		}

		$('.oauth_social_box_wrapper').show();

		$('.oauth_more_options').bind('click', function(e) {
			$.cookie('oauth', null, options);
			$('.oauth_social_box_wrapper .ysi_oauth_signin').each(function(idx) {
				$(this).parent().show();
			});
			$('.oauth_more_options').hide();
		});
	}

	function openSocialConnect(pageURL, title, w, h) {
		var left = (screen.width/2)-(w/2);
		var top = (screen.height/2)-(h/2);
		var features = 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left;

		if( pageURL.indexOf("http:") === -1 && pageURL.indexOf("https:") === -1 && window.web_phi_url )
			pageURL = "https://" + window.web_phi_url + (pageURL.indexOf("/") === 0 ? '' : '/') + pageURL;

		return window.open(pageURL, '', features);
	}

	function setOAuthDialogDefaults() {
		$.extend($.ui.dialog.defaults, {
			height: 'auto',
			width: 'auto',
			modal: true,
			bgiframe: true,
			resizable: false,
			closeOnEscape: true,
			autoOpen: false,
			hide: 'slide'
		});

	}

	function isLogin() {
		if ($.cookie ("acct")) {
			var cookieAcct = $.cookie("acct").split(",");
			if ( cookieAcct[0] != 'GST' ) {
				return true;
			}
		}
		return false;
	}

	function logout() {
		var options = {domain: 'hightail.com', path:'/'};

		$.cookie('Ysi_session_id', null, options);
		$.cookie('auth', null, options);
		$.cookie('acct', null, options);
		$.cookie('uname', null, options);
		$.cookie('oauth_nonce', null, options);

		try {
			var oauthJson = $.JSON.decode($.cookie('oauth'));
			oauthJson.user_registed = '';
			oauthJson.user_login = false;
			oauthJson = $.JSON.encode(oauthJson);

			options = {domain: 'hightail.com', path:'/'};
			$.cookie('oauth', oauthJson, options);
		} catch(e) {}

	}

	function getAct() {
		return act;
	}

	// YSI.OAuth public API
	return {
		batchId: batchId,
		urlParams: '',
		init: init,
		setCallBack: setCallBack,
		getAct: getAct,
		setClickCallBack: setClickCallBack
	};
})();

YSI.OAuth.providers = {'yahoo': 'Yahoo!', 'google': 'Google'};

